directives.directive('tableCounter', ["$rootScope", "tools","$timeout", function ($rootScope, tools,$timeout) {
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        templateUrl: "/trend-new-BI/app/components/dbManager/tableCounter/tableCounterView.html",
        link: function (scope, element, attr) {

            scope.table1 = {}; //表1
            scope.msg = null;
            scope.counterArry = [];
            scope.indexInArry = [];//xuan
            scope.expressionTitle = '';

            $('.menu .item').tab();
            scope.counter = ['+','-','*','/','%'];//0,1,2,3,4
           // scope.counter = ['＋','－','*','/','%'];//0,1,2,3,4
            $('.radio.checkbox').checkbox();


            /**
             * 获取字段
             * @param tbId
             * @param tableType
             * @param index  第几个表 表1 or 表2
             */
            function getFiled(tbId, tableType, index) {
                tools.get({
                    method: 'POST',
                    url: '/Ibm-Client/getSingleTable.htm',
                    data: {
                        tbId: tbId,
                        tableType: tableType
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            if (index == 1) {
                                scope.table1.filed = resp.value.columns;
                               // console.log(scope.table1.filed);
                            } else {
                                scope.table2.filed = resp.value.columns;
                            }
                        }else{
//                            alert(resp.message);
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
            }
            /**
             * $rootScope
             */
            $rootScope.$on('Show_CounterView_EV', function (e, data) {

                scope.ArryForDesc = [];
                $timeout(function(){
                    $(element).modal('show');
                },500);
                //$(element).modal('show');
               // console.log(data);
                scope.table1.table = data;
                getFiled(data.tbId, data.tableType, 1);

            });


            //运算检查 前-后
            function isStuff(oldPos,newPos){
                //当oldPos是‘（’，newPos不能为运算符号+-*/)
               // console.log('oldPos:'+oldPos+"  newPos"+newPos);
                if(oldPos == '(' ){
                    if(newPos == 0 || newPos== ')'){
                        scope.msg = "请正确选择运算符号";
                        $timeout(function(){
                            scope.msg = '';
                        },3000);
                      //  console.log('error-1：’（');
                        return true;

                    }
                }
                //字段 （
                if(oldPos == '数字' ){
                    if(newPos != 0 && newPos != ')'){
                        scope.msg = "请正确选择运算符号";
                        $timeout(function(){
                            scope.msg = '';
                        },3000);
                       // console.log('error-5：数字');
                        return true;

                    }
                }
                //当oldPos是‘)’，newPos不能为运算符号(数字字段
                if(oldPos == ')'){
                    if(newPos != 0 && newPos != ')'){
                        scope.msg = "请正确选择运算符号";
                        $timeout(function(){
                            scope.msg = '';
                        },3000);
                       // console.log('error-2：’)');
                        return true;
                    }
                }

                //当oldPos是运算符号+-*/，newPos不能为运算符号+-*/
                if(oldPos == 0 && newPos ==0){
                    scope.msg = "请正确选择运算符号";
                    $timeout(function(){
                        scope.msg = '';
                    },3000);
                   // console.log('error-3：’（');
                    return true;
                }

                //当oldPos是字段或数字（），newPos不能为字段或数字（）
                if(oldPos != 0 && newPos !=0 && oldPos != '(' && oldPos != ')' && newPos != '(' && newPos != ')'){

                    scope.msg = "请正确选择运算符号";
                    $timeout(function(){
                        scope.msg = '';
                    },3000);
                   // console.log('error-4：’（');
                    return true;
                }
            }


            scope.older = null;//记录位置---默认length长度从1开始
            scope.ArryForDesc = [];


            var reordering=function($elements){
            };
            var reordered=function($elements){
               // console.log("reordered");
                scope.ArryForDesc=[];
                for(var i=0;i<$elements.length;i++){
                    //console.log($elements[i].id);
                    scope.ArryForDesc.push(Number($elements[i].id));

                }

            };





            scope.Addnumber = function(number){
                var length=scope.counterArry.length;
                if(length==0){
                    scope.counterArry.push({desc:number,name:number,column:"数字"});
                    scope.ArryForDesc.push(scope.counterArry.length-1);
                    scope.indexInArry[0] = 1;
                    scope.older=1;
                    return;
                }

                if(scope.counterArry[length-1].column=="数字"){
                    scope.counterArry[length-1].desc=scope.counterArry[length-1].desc+""+number;
                    scope.counterArry[length-1].name=scope.counterArry[length-1].name+""+number;
                }else{
                    scope.counterArry.push({desc:number,name:number,column:"数字"});
                    scope.ArryForDesc.push(scope.counterArry.length-1);
                    scope.indexInArry[length-1] = -1;
                    scope.indexInArry[length] = 1;scope.older++;
                }

                $timeout(function(){
                    $('.gridly').gridly({
                        base: 100, // px
                        gutter: 10, // px
                        columns: 6,
                        callbacks:{ reordering: reordering , reordered: reordered }
                    });
                },100);

            };


            /**
             * 添加运算
             * @param text
             * @param column
             */
            scope.addToCounter = function (text,column) {
               // console.log("older:"+scope.older);
                //长度
                var length = scope.counterArry.length;
                //$timeout(function(){ $('.gridly').gridly();console.log($(".gridly"))},500);
                if( length == 0){
                    if(column == 0){
                        scope.msg = "请选择正确的运算表达";
                        $timeout(function(){
                            scope.msg = null;
                        },3000);
                        return;
                    }
                    if(column=='(' || column==')'){
                        scope.counterArry.push({desc:text, name: column, column:column});
                        scope.indexInArry.push(scope.counterArry.length);
                        scope.ArryForDesc.push(scope.counterArry.length-1);

                    }else{
                        scope.counterArry.push({desc:text, name:'table[0].'+column, column:column});
                        scope.indexInArry.push(scope.counterArry.length);
                        scope.ArryForDesc.push(scope.counterArry.length-1);

                    }
                   

                    $timeout(function(){
                        $('.gridly').gridly({
                            base: 100, // px
                            gutter: 10, // px
                            columns: 6,
                            callbacks:{ reordering: reordering , reordered: reordered }
                        });
                    },100);
                    scope.older = 1;
                    return;
                }
               // console.log('acv');
               // console.log(text+" "+column);

                if(length<scope.older){
                    scope.msg = "请选择要插入的位置";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }



                //运算不匹配错误
                if(isStuff(scope.counterArry[scope.older-1].column,column)){
                    return;
                }
                //处于最后一个位置
                if(length == scope.older){

                    scope.indexInArry[length-1] = -1;

                    if(column==0){
                        scope.counterArry.push({desc:text,name: text, column:0});
                        scope.indexInArry.push(scope.counterArry.length);
                        scope.ArryForDesc.push(scope.counterArry.length-1);

                    }else if(column=='(' || column==')'){
                        scope.counterArry.push({desc:text, name: column, column:column});
                        scope.indexInArry.push(scope.counterArry.length);
                        scope.ArryForDesc.push(scope.counterArry.length-1);

                    }else{
                        scope.counterArry.push({desc:text, name:'table[0].'+column, column:column});
                        scope.indexInArry.push(scope.counterArry.length);
                        scope.ArryForDesc.push(scope.counterArry.length-1);

                    }
                    scope.older++;
                    $timeout(function(){
                        $('.gridly').gridly({
                            base: 100, // px
                            gutter: 10, // px
                            columns: 6,
                            callbacks:{ reordering: reordering , reordered: reordered }
                        });
                    },100);
                    return;

                }else{//不是处于最后一个

                    //旧的位置
                    scope.indexInArry[scope.older-1] = -1;

                    //在scope.older的位置上插入
                    if(column==0 || column=='(' || column==')'){
                        scope.counterArry.splice(scope.older,0,{desc:text,name: text, column:0});
                        scope.indexInArry.splice(scope.older,0,scope.older+1);
                        scope.ArryForDesc.push(scope.counterArry.length-1);
                    }else{
                        scope.counterArry.splice(scope.older,0,{desc:text,name:'table[0].'+column, column:column});
                        scope.indexInArry.splice(scope.older,0,scope.older+1);
                        scope.ArryForDesc.push(scope.counterArry.length-1);
                    }
                    scope.older = scope.older+1;
                    $timeout(function(){
                        $('.gridly').gridly({
                            base: 100, // px
                            gutter: 10, // px
                            columns: 6,
                            callbacks:{ reordering: reordering , reordered: reordered }
                        });
                    },100);
                }

              //  console.log(scope.counterArry);
              //  console.log(scope.indexInArry);
            };


            //改变默认位置--字段的选中---只能选一个
            scope.btnActive = function($index){ //$index--0,1,2,3....

                event.preventDefault();
                event.stopPropagation();
                $('.gridly').gridly('layout');

               // console.log('scope.older:'+scope.older+"  $index:"+$index);
                var length = scope.indexInArry.length;
                //点击最后一个，scope.older不改变过,olde与长度相等-默认
                if(length == scope.older && $index == length-1){
                    return;
                }else{//点击其他位置，改变scope.older的大小
                    if(scope.older == $index+1){
                        scope.older = length;
                        scope.indexInArry[$index] = -1;
                        scope.indexInArry[scope.older-1] = scope.older;//定位到最后一个
                        return;
                    }

                    scope.indexInArry[scope.older-1] = -1;

                    //scope.older改变
                    scope.older = $index+1;

                    scope.indexInArry[scope.older-1] = scope.older;


                }
            };


            //删除运算
            scope.delCounArry = function ($index,e) {

                e.stopPropagation();

                //e.preventDefault();
              //  console.log('1.0.scope.older:'+scope.older);
                var length =scope.indexInArry.length;
             //   console.log('long:'+length);
                scope.counterArry.splice($index,1);
                scope.indexInArry.splice($index,1);
                scope.ArryForDesc.splice($index,1);
                $('.gridly').gridly('layout');



                //！！真实长度已经改变。。。。

                //删除最后一个位置
                if(length-1 == $index && scope.older == length){
                    scope.indexInArry[length-2] = length-1;
                    scope.older--;
                }else{
                    if(scope.older == $index+1){
                      //  console.log('scope.older=:'+scope.older);
                        scope.indexInArry[scope.older-1] = scope.older;
                        return;
                    }
                    if($index+1<scope.older){
                     //   console.log("scope.older>:"+scope.older);
                        scope.indexInArry[scope.older-1] = -1;
                        scope.older--;
                        scope.indexInArry[scope.older-1] = scope.older;
                        return;
                    }
                }

            };
            /*
            //数字的界面显示
            scope.numShowFun = function(){
                scope.numShow = true;
               //$("#numTxt").focus();
                //document.getElementById('numTxt').focus();
                console.log(document.getElementById('numTxt'));
            };
            //确认数字
            scope.numT = null;
            scope.numOk = function () {
                var reg = new RegExp("^[0-9]*$");
                if (!reg.test(scope.numT)){
                    scope.msg = '请输入数字';
                    $timeout(function(){
                        scope.msg = '';
                        scope.numT = null;
                    },2000);
                    return;
                }else{
                    if(scope.older == scope.indexInArry.length){
                        scope.indexInArry[scope.older-1] = -1;
                        scope.older++;
                        scope.counterArry.push({desc:tools.trim(scope.numT),name:tools.trim(scope.numT),column:'数字'});
                        scope.indexInArry.push(scope.indexInArry.length);
                    }else{
                        scope.indexInArry[scope.older-1] = -1;
                        scope.counterArry.splice(scope.older,0,{desc:tools.trim(scope.numT),name:tools.trim(scope.numT),column:'数字'});
                        scope.indexInArry.splice(scope.older,0,scope.older+1);
                        scope.older = scope.older+1;
                    }

                    $timeout(function(){
                        $('.gridly').gridly({
                            base: 100, // px
                            gutter: 10, // px
                            columns: 6,
                            callbacks:{ reordering: reordering , reordered: reordered }
                        });
                    },100);
                    scope.numShow = false;
                    scope.numT = null;
                }
            };
*/
/*------------------------------------step2-----------------------------------------*/
            /**
             * 函数运算
             * @param text 函数度名称
             * @param exp 函数度express
             */
            scope.funToCounter = function(text,exp){
                var length = scope.counterArry.length;
                if(length == 0){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                if(scope.counterArry[scope.older-1].column==0){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                var obj = scope.counterArry[scope.older-1];
                obj.oldDesc = obj.desc;
                obj.desc =text+'( '+obj.desc+' )';
                obj.name = exp+'( '+obj.name+' )';
                obj.expression = exp;

              //  console.log(scope.counterArry);
            };

            var jsonCut = {};//cut
            scope.matchCut = {};
            scope.radioValue='+';


            //截取btn点击事件
            scope.cutFiled = function(text,exp,index){

                if(scope.counterArry.length==0){
                    scope.msg = "请选择要操作的字段";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                if(scope.counterArry[scope.older-1].column==0 && scope.older!=null){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                if(index == 3){
                    scope.substring = true;
                }
                if(index == 4){
                    scope.substring_index = true;
                }
                jsonCut = {};
                scope.cutFShow = true;
                scope.cutFiledInput = null;
                jsonCut.text = text;
                jsonCut.exp = exp;
                jsonCut.index = index;
            };
            //取消长度截取
            scope.cutFiledCancel = function(){

              //  console.log("jsonCut:"+JSON.stringify(jsonCut));
              //  console.log('scope.matchCut:'+JSON.stringify(scope.matchCut));
                scope.cutFShow=false;
                scope.cutFiledInputStart = null;
                scope.cutFiledInputEnd = null;
                scope.substring = scope.substring_index = false;
                jsonCut = {};
                scope.matchCut = {};
            };
            //确认长度截取
            scope.cutFiledOk = function(){
                var reg = new RegExp("^[0-9]*$");
                //普通截取
                if((!reg.test(scope.cutFiledInput)) && (jsonCut.index == 1 || jsonCut.index == 2)){
                    scope.msg = "请输入数字";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                //定位截取
                if(((!reg.test(scope.cutFiledInputStart)) || (!reg.test(scope.cutFiledInputEnd))) && jsonCut.index == 3){
                    scope.msg = "请输入数字";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                //匹配截取
                if((scope.matchCut.matchMsg == null || scope.matchCut== null)&&(jsonCut.index ==4)){
                    scope.msg = "请输入匹配内容";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                if((!reg.test(scope.matchCut.matchIndex)) && (jsonCut.index == 4)){
                    scope.msg = "请输入数字";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                var obj = scope.counterArry[scope.older - 1];
                //普通截取
                if(jsonCut.index == 1 || jsonCut.index == 2) {
                    obj.oldDesc = obj.desc;
                    obj.desc = jsonCut.text + '( ' + obj.desc + ',' + scope.cutFiledInput + ' )';
                    obj.name = jsonCut.exp + '( ' + obj.name + ',' + scope.cutFiledInput + ' )';
                    obj.expression = jsonCut.exp;
                //定位截取
                }else if(jsonCut.index == 3){
                    obj.oldDesc = obj.desc;
                    obj.desc = jsonCut.text + '( ' + obj.desc + ',' + scope.cutFiledInputStart + ' , '+scope.cutFiledInputEnd+')';
                    obj.name = jsonCut.exp + '( ' + obj.name + ',' +  scope.cutFiledInputStart + ' , '+scope.cutFiledInputEnd + ' )';
                    obj.expression = jsonCut.exp;
                //匹配截取
                }else if(jsonCut.index == 4){
                    obj.oldDesc = obj.desc;
                    obj.desc = jsonCut.text + '( ' + obj.desc + ', \'' + scope.matchCut.matchMsg + '\' , '+scope.radioValue+''+scope.matchCut.matchIndex+')';
                    obj.name = jsonCut.exp + '( ' + obj.name + ', \'' +  scope.matchCut.matchMsg + '\' , '+scope.radioValue+''+scope.matchCut.matchIndex+')';
                    obj.expression = jsonCut.exp;
                }

              //  console.log(scope.matchCut.radioValue);
                scope.cutFShow=false;
                scope.substring = scope.substring_index = false;
                scope.cutFiledInputStart = null;
                scope.cutFiledInputEnd = null;
                scope.matchCut = {};
                //jsonCut = {};
              //  console.log("obj:"+JSON.stringify(obj));
            };

/*-------------------------new Date data--------------------------*/
            scope.dateData = [
                {
                    text:'年份',
                    exp:'EXTRACT(YEAR FROM '
                },
                {
                    text:'季度',
                    exp:'EXTRACT(QUARTER FROM '
                },
                {
                    text:'年月',
                    exp:'EXTRACT(YEAR_MONTH FROM '
                },
                {
                    text:'月份',
                    exp:'EXTRACT(MONTH FROM '
                },
                {
                    text:'周',
                    exp:'EXTRACT(WEEK FROM  '
                },
                {
                    text:'日',
                    exp:'EXTRACT(DAY FROM '
                }
            ];
            scope.newDateSelect = [
                {
                    id: 0,
                    exp: "DAY",
                    text: '天'
                },
                {
                    id: 1,
                    exp:"WEEK",
                    text:'周'
                },
                {
                    id: 2,
                    exp:"MONTH",
                    text:'月'
                },
                {
                    id: 3,
                    exp:"QUARTER",
                    text:'季'
                },
                {
                    id: 4,
                    exp:"YEAR",
                    text:'年'
                },
                {
                    id: 5,
                    exp:"HOUR",
                    text:'小时'
                },
                {
                    id: 6,
                    exp:"MINUTE",
                    text:'分钟'
                },
                {
                    id: 7,
                    exp:"SECOND",
                    text:'秒'
                }
            ];
            scope.newDateValue ={};
            scope.newDateClick = function(){
//                console.log("scope.older: " + scope.older);
//                console.log(scope.counterArry);
                if(scope.counterArry.length==0){
                    scope.msg = "请选择要操作的字段";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                if(scope.counterArry[scope.older-1].column==0 && scope.older!=null){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }

                scope.newDatePanel= true;
            };
            scope.dateToCounter = function(text,exp){
                var length = scope.counterArry.length;
                if(length == 0){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                if(scope.counterArry[scope.older]!=null && scope.counterArry[scope.older].column==0){
                    scope.msg = '请选择字段';
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                var obj = scope.counterArry[scope.older-1];
                obj.oldDesc = obj.desc;
                obj.desc =text+'( '+obj.desc+' )';
                obj.name = exp+obj.name+' )';
                obj.expression = exp;

//                console.log(scope.counterArry);
            };

            //取消
            scope.newDateCancel = function(){
                scope.newDatePanel= false;
                scope.newDateValue ={};

            };

            //确认
            scope.newDateOk =function(){
//                console.log(scope.newDateValue);
                var reg = new RegExp("^[0-9]*$");
                if(!reg.test(scope.newDateValue.numValue)){
                    scope.msg = "请输入数字";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                if(scope.newDateValue.selectValue == null){
                    scope.msg = "请选择数值类型";
                    $timeout(function(){
                        scope.msg = null;
                    },3000);
                    return;
                }
                var obj = scope.counterArry[scope.older-1];
                obj.oldDesc = obj.desc;
                obj.desc ="日期添加"+'( '+obj.desc+' , '+scope.newDateValue.numValue+scope.newDateSelect[scope.newDateValue.selectValue].exp+' )';
                obj.name = "DATE_ADD("+obj.name+',INTERVAL '+scope.newDateValue.numValue+' '+scope.newDateSelect[scope.newDateValue.selectValue].exp+' )';
                obj.expression = scope.newDateSelect[scope.newDateValue.selectValue].exp;
                scope.newDatePanel= false;
                scope.newDateValue ={};
            };
/*--------------------------------------------------------------------------------------*/
            function init(){

                scope.table1 = {}; //表1
                scope.msg = null;
                scope.counterArry = [];
                scope.indexInArry = [];
                scope.expressionTitle = '';
                scope.numT = null; //数字input
                scope.cutFShow=false;
                scope.substring_index = false;
                scope.substring = false;
                scope.cutFiledInputStart = null;
                scope.cutFiledInputEnd = null;
                scope.older = null;
                scope.newDatePanel =false;
            }
            //取消
            scope.cancel = function () {
                $(element).modal('hide');
                init();
            };

            //确认
            scope.ok = function () {


                //
                if (scope.numShow) {
                    scope.msg = '请先确认数字';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }
                if(scope.newDatePanel){
                    scope.msg = '请先确认日期';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }
                //字段名称检查
                if (scope.expressionTitle == '') {
                    scope.msg = '请输入字段名';
                    $('#exTitle').focus();
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }else{
                    var bool = false;
                    angular.forEach(scope.table1.filed,function(item){
                        if(item.columnDesc == scope.expressionTitle){
                            scope.msg = '该字段名称已存在';
                            $timeout(function(){
                                scope.msg = null;
                            },3000);
                            bool = true;
                            return;
                        }
                    });
                    if(bool){
                        return;
                    }
                }

                if (scope.counterArry[0]==null) {
                    scope.msg = '请选择运算';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }

                if(scope.cutFShow){
                    scope.msg = '请确认截取';
                    $timeout(function(){
                        scope.msg = null;
                    },2000);
                    return;
                }
                var exp = '';
                var desc = '';
//                console.log("counterArry");
//                console.log(scope.counterArry);
//                console.log("序列号");
//                console.log(scope.ArryForDesc);


                angular.forEach(scope.ArryForDesc,function(item){
                    exp += scope.counterArry[item].name;
                    desc += scope.counterArry[item].desc;
                });

               /* console.log({
                    tbId: scope.table1.table.tbId,
                    tableType: scope.table1.table.tableType,
                    expression: exp,
                    desc: desc,
                    expressionTitle: scope.expressionTitle,
                    type:'addExpression'
                });*/


                tools.post({

                    url:'/Ibm-Client/addExpressionColumn.htm',
                    data:{
                        tbId: scope.table1.table.tbId,
                        tableType: scope.table1.table.tableType,
                        expression: exp,
                        desc: desc,
                        expressionTitle: scope.expressionTitle,
                        type:'addExpression'
                    },
                    succ:function (resp) {
                        if (resp.success) {
                            $rootScope.$broadcast('update_tableCounter_EV',scope.table1.table.tbId,scope.table1.table.tableType);
                            $(element).modal('hide');
                            $rootScope.$broadcast('MESSAGE_EV','添加字段成功');
                            scope.counterArry = [];
                            init();
                        }else{
                            scope.msg = resp.message;
                            $timeout(function(){
                                scope.msg = null;
                            },2000);
                        }
                    }
                });

            };
        }
    };
}]);